import type { FC, MouseEventHandler } from 'react';
import { Tooltip } from 'antd';
import { useMemo } from 'react';
import classNames from 'classnames';
import { useMemoizedFn } from 'ahooks';
import Icon from '../Icon';
import type { ToolButtonProps, ToolButtonWrapperProps } from './types';
import styles from './styles.module.less';

type MouseFn = MouseEventHandler<Element>;

export const ToolButtonWrapper: FC<ToolButtonWrapperProps> = (props) => {
  const {
    title,
    onClick,
    tooltip,
    children,
    selected = false,
    enableHover = true
  } = props;

  const extEle = props.renderExtElem?.();

  const className = useMemo(() => {
    return classNames(
      styles.tool_button,
      enableHover && styles.hover,
      selected && styles.selected
    );
  }, [selected, enableHover]);

  const handleClick = useMemoizedFn<MouseFn>((evt) => {
    evt.stopPropagation();
    onClick?.(evt);
  });

  return (
    <Tooltip
      title={tooltip}
      placement="right"
      trigger={['click', "hover"]}
    >
      <div
        title={title}
        onClick={handleClick}
        className={className}
      >
        {children}
        {extEle}
      </div>
    </Tooltip>
  );
}

const ToolButton: FC<ToolButtonProps> = (props) => {
  return (
    <ToolButtonWrapper {...props}>
      <Icon {...props} />
    </ToolButtonWrapper>
  );
}

export default ToolButton;